﻿#region Copyright and License Notice
// Copyright (C)2010-2016 - Rob Levine and other contributors
// http://configgen.codeplex.com
// 
// This file is part of ConfigGen.
// 
// ConfigGen is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// ConfigGen is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License and 
// the GNU Lesser General Public License along with ConfigGen.  
// If not, see <http://www.gnu.org/licenses/>
#endregion

using System;
using System.Data;
using log4net;

namespace ConfigGen.Core.SettingsLoader
{
    /// <summary>
    /// Loads spreadsheet preferences (such as the number of columns to skip when parsing a settings spreadsheet) from the spreadsheet.
    /// </summary>
    public class SpreadsheetPreferencesLoader : ISpreadsheetPreferencesLoader
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (SpreadsheetPreferencesLoader));

        /// <summary>
        /// Gets the spreadsheet preferences from the spreadsheet, if any, otherwise returns the default preferences.
        /// </summary>
        /// <param name="spreadsheetPreferences">Dataset containing the preferences "worksheet", if any.</param>
        /// <returns>Spreadsheet preferences.</returns>
        public SpreadsheetPreferences GetSpreadsheetPreferences(DataSet spreadsheetPreferences)
        {
            if (spreadsheetPreferences == null)
            {
                throw new ArgumentNullException("spreadsheetPreferences");
            }

            var preferences = SpreadsheetPreferences.GetDefaultPreferences();

            if (!spreadsheetPreferences.Tables.Contains("Preferences"))
            {
                Log.Debug("'Preferences' worksheet not found in spreadsheet - returning default preferences");
                return preferences;
            }

            var preferencesTable = spreadsheetPreferences.Tables["Preferences"];

            if (preferencesTable.Columns.Count < 1 || preferencesTable.Rows.Count == 0)
            {
                Log.Debug("'Preferences' worksheet found but contained no usable data - returning default preferences");
                return preferences;
            }

            foreach (DataRow row in preferencesTable.Rows)
            {
                var preferenceName = row[0];
                var preferenceValue = preferencesTable.Columns.Count == 1?string.Empty:row[1];

                if (!CellDataParser.IsCellEmpty(preferenceName))
                {
                    ParseAndApplyPreference(
                        preferenceName.ToString(), 
                        CellDataParser.IsCellEmpty(preferenceValue)?string.Empty:preferenceValue.ToString(),
                        preferences);
                }
            }

            return preferences;
        }

        private void ParseAndApplyPreference(string preferenceName, string preferenceValue, SpreadsheetPreferences targetPreferences)
        {
            switch (preferenceName)
            {
                case "NumColumnsToSkip":
                    int numColumnsToIgnore;
                    if (int.TryParse(preferenceValue, out numColumnsToIgnore))
                    {
                        Log.DebugFormat("SpreadsheetPreference: NumColumnsToSkip={0}", numColumnsToIgnore);
                        targetPreferences.NumColumnsToSkip = numColumnsToIgnore;
                    }
                    else
                    {
                        Log.WarnFormat(
                            "The supplied value for spreadsheet preference 'NumColumnsToSkip' could not be parsed: {0}",
                            preferenceValue);
                    }
                    break;
                case "EmptyStringPlaceholder":
                    Log.DebugFormat("SpreadsheetPreference: EmptyStringPlaceholder={0}", preferenceValue);
                    targetPreferences.EmptyStringPlaceholder = preferenceValue;
                    break;
                case "NullPlaceholder":
                    Log.DebugFormat("SpreadsheetPreference: NullPlaceholder={0}", preferenceValue);
                    targetPreferences.NullPlaceholder = preferenceValue;
                    break;
                default:
                    Log.WarnFormat("The following spreadsheet preference was not recognised and has been ignored: {0}", preferenceValue);
                    break;
            }
        }
    }
}
